package com.example.shopp_2301.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.base.entity.LoginEntityResult
import com.example.base.entity.SendCodeEntity
import com.example.base.entity.SendCodeEntityResult
import com.example.base.entity.UserEntityResult
import com.example.base.mvvm.BaseModel
import com.example.base.mvvm.BaseViewModel
import com.example.shopp_2301.utils.SingleLiveData
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class LoginViewModel:BaseViewModel() {
    //定义两个返回值 ---成功和失败
    val sendCodeFail = SingleLiveData<String>()
    val sendCodeSuccess = SingleLiveData<BaseModel<SendCodeEntity>>()
    //封装方法，实现调用
    fun sendCode(phone:String){
        viewModelScope.launch {
            try {
                sendCodeSuccess.setValue(apiServer.sendCode(phone))
            }catch (e:Exception){
                sendCodeFail.setValue(e.message.toString())
            }

        }
    }
    //返回值---验证码登录
    val loginCodeSuccess = MutableLiveData<LoginEntityResult>()
    val loginCodeFail = MutableLiveData<String>()
    //封装方法，实现调用
    fun loginCode(captcha:String,phone:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map.put("captcha",captcha)
                map.put("phone",phone)
                loginCodeSuccess.value = apiServer.loginCode(mapToBody(map))
            }catch (e:Exception){
                loginCodeFail.value = e.message
            }
        }
    }
    //返回值---密码登录
    val loginSuccess = MutableLiveData<LoginEntityResult>()
    val loginFail = MutableLiveData<String>()
    fun login(account:String,password:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["account"] = account
                map["password"] = password
                loginSuccess.value = apiServer.login(mapToBody(map))
            }catch (e:Exception){
                loginFail.value = e.message
            }
        }
    }
    //返回值--获取用户信息
    val userSuccess = MutableLiveData<UserEntityResult>()
    val userFail = MutableLiveData<String>()
    fun user(){
        viewModelScope.launch {
            try {
                userSuccess.value = apiServer.user()
            }catch (e:Exception){
                userFail.value = e.message
            }
        }
    }
}